package Game.Objects;

import java.lang.reflect.InvocationTargetException;

import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;

import GUI.GuiManager;
import GUI.GuiMessenger;
import Game.Level;
import Screens.MyScreens.GameScreen;
import Tools.SoundManager;
import Tools.Drawing.LayersHelper;

/** Trapdoor 
 * @author Aikidos
 */
public class GOTrapdoor extends GameObject {

	/** Is close? */
	private boolean _isClose = true;
	
	public GOTrapdoor(ObjectManager objectManager) throws SlickException {
		super(objectManager, "Trapdoor");
		
		setSprite(new Image("res/gfx/trapdoor_close.png"));
		setLayerForDrawing(LayersHelper.LAYER_OBJECTS);
		
		_isCanBeUsed = true;
	}
	
	/** Returns true if trapdoor is close
	 * @return True if trapdoor is close
	 */
	public boolean isClose() {
		return _isClose;
	}
	
	/** Open trapdoor */
	public void open() throws SlickException {
		setSprite(new Image("res/gfx/trapdoor_open.png"));
		_isClose = false;
	}
	
	/** Close trapdoor */
	public void close() throws SlickException {
		setSprite(new Image("res/gfx/trapdoor_close.png"));
		_isClose = true;
	}

	@Override
	public void use(GameObject user) throws SlickException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException {
		if (user.isPlayer()) {
			GOPlayer player = (GOPlayer)user;
			
			if (_isClose) {
				GuiManager.getMessenger().addMessage("[yellow]" + this.getName() + "[/yellow] is closed!");
				
				// Play sound
				SoundManager.play("sfx_door_lock");
			}
			else {
				// Increase floor
				GameScreen gameScreen = (GameScreen) _objectManager.getLevel().getScreen();
				gameScreen.setFloor(gameScreen.getFloor() + 1);
				
				// Clear gui map marks
				GuiManager.getGuiMap().clearMarks();
				
				// Delete all door keys
				for (int i = 0; i < player.getInventory().getItems().size(); i++) {
					if (player.getInventory().getItems().get(i).getClass().getName() == "Game.Items.Others.GIDoorKey") {
						player.getInventory().getItems().remove(i);
						i = 0;
					}
				}
				
				// Recreate level
				_objectManager.getLevel().create(gameScreen.getFloor(),
						gameScreen.getDefaultSpawners());
			}
		}
	}
}
